from drf_haystack.serializers import HaystackSerializer
from rest_framework import serializers
from django_redis import get_redis_connection

from goods.models import SKU
from goods.search_indexes import SKUIndex
from goods.utils import PageNum


class CartSerializer(serializers.Serializer):

    sku_id = serializers.IntegerField(min_value=1)
    count = serializers.IntegerField(min_value=1)
    selected = serializers.BooleanField(default=True)

    def validate(self, attrs):
        # 判断商品和库存
        try:
            sku = SKU.objects.get(id = attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')

        if attrs['count'] > sku.stock:
            raise serializers.ValidationError('商品数量不足')

        return attrs


class CartDeleteSerializer(serializers.Serializer):

    sku_id = serializers.IntegerField(min_value=1)

    def validate(self, attrs):
        # 判断商品和库存
        try:
            sku = SKU.objects.get(id = attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')

        return attrs


class CartSelectionSerializer(serializers.Serializer):

    selected = serializers.BooleanField()


class SKUSerializer(serializers.ModelSerializer):

    count = serializers.IntegerField(read_only=True)
    selected = serializers.BooleanField(read_only=True)

    class Meta:
        model = SKU
        fields = '__all__'




